package com.sgy.netty;

import com.sgy.netty.codec.MessageCodec;
import com.sgy.netty.codec.MessageDecoder;
import com.sgy.netty.codec.MessageEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.nio.NioIoEvent;
import io.netty.channel.socket.nio.NioSocketChannel;

public class NettyClient {

    public static void main(String[] args) throws InterruptedException {
        // 创建线程组
        EventLoopGroup group = new NioEventLoopGroup();

        // 创建客户端启动助手
        Bootstrap bootstrap = new Bootstrap();

        // 设置线程组
        bootstrap.group(group)
                .channel(NioSocketChannel.class)  // 设置客户端通道实现为nio
                .handler(new ChannelInitializer<Channel>() {  // 创建一个通道初始化对象
                    @Override
                    public void initChannel(Channel ch) throws Exception {
                        // 添加解码器
                        // ch.pipeline().addLast("messageDecoder", new MessageDecoder());
                        // 添加编码器
                        // ch.pipeline().addLast("messageEncoder", new MessageEncoder());

                        // 添加编解码器
                        ch.pipeline().addLast(new MessageCodec());
                        // 向pipeline中添加自定义业务处理handler
                        ch.pipeline().addLast(new NettyClientHandler());
                    }
                });

        // 启动客户端，等待连接服务器，同时将异步改为同步
        ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 9999).sync();

        // 关闭通道和关闭连接池
        channelFuture.channel().closeFuture().sync();
        group.shutdownGracefully();
    }
}
